<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="入库仓库" prop="rukuCangku">
        <el-input
          v-model="queryParams.rukuCangku"
          placeholder="请输入入库仓库"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库日期" prop="rukuRukudate">
        <el-date-picker clearable
          v-model="queryParams.rukuRukudate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择入库日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['jiuzai:wuziruku:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
    <!-- 新增的查看按钮 -->
    <el-button
      type="info"
      plain
      icon="View"
      @click="handleBatchView"
      v-hasPermi="['jiuzai:wuziruku:query']"
    >查看</el-button>
  </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['jiuzai:wuziruku:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['jiuzai:wuziruku:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['jiuzai:wuziruku:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="wuzirukuList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="rukuId" />
      <el-table-column label="仓库" align="center" prop="kuId" >
        <template #default="scope">
          <span v-if="scope.row.kuId ===  scope.row.kuId">
            {{ scope.row.cangku?.kuName}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="入库人" align="center" prop="yId">
        <template #default="scope">
          <span v-if="scope.row.yId ===  scope.row.yId">
            {{ scope.row.table12?.yName}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="入库单号" align="center" prop="rukuDanhao" />
      <el-table-column label="采购批次" align="center" prop="rukuPici" />
      <el-table-column label="入库日期" align="center" prop="rukuRukudate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.rukuRukudate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="捐赠用途" align="center" prop="rukuTongtu" />
      <el-table-column label="物资来源" align="center" prop="rukuLaiyuan" />
      <el-table-column label="dizhi" align="center" prop="dizhiId" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['jiuzai:wuziruku:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['jiuzai:wuziruku:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改wuziruku对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="wuzirukuRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="仓库" prop= kuId >
          <!-- <el-input v-model="form.kuId" placeholder="请输入仓库" /> -->
           <!-- 下拉框 -->
            <el-select v-model="form.kuId" placeholder="请选择仓库">
              <el-option
                v-for="item in cangkuList"
                :key="item.kuId"
                :label="item.kuName"
                :value="item.kuId"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="入库人" prop="yId">
          <el-select v-model="form.yId" placeholder="请选择用户">
            <el-option
              v-for="item in wuziList"
              :key="item.yId"
              :label="item.yName"
              :value="item.yId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入库单号" prop="rukuDanhao">
          <el-input v-model="form.rukuDanhao" placeholder="请输入入库单号" />
        </el-form-item>
        <el-form-item label="采购批次" prop="rukuPici">
          <el-input v-model="form.rukuPici" placeholder="请输入采购批次" />
        </el-form-item>
        <el-form-item label="入库日期" prop="rukuRukudate">
          <el-date-picker clearable
            v-model="form.rukuRukudate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择入库日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="捐赠用途" prop="rukuTongtu">
          <el-input v-model="form.rukuTongtu" placeholder="请输入捐赠用途" />
        </el-form-item>
        <el-form-item label="物资来源" prop="rukuLaiyuan">
          <el-input v-model="form.rukuLaiyuan" placeholder="请输入物资来源" />
        </el-form-item>
        <!-- 物资详细 -->
         <el-form-item label="物资详细" prop="rukuXiangqing">
          <el-button 
      type="success" 
      plain 
      icon="Select" 
      @click="handleSelectMingxi"
      v-hasPermi="['jiuzai:wuziruku:add']"
    >选择物资</el-button>
      <!-- 显示已选择的物资明细 -->
      <el-table :data="form.mingxiList || []" border style="margin-top: 10px;">
  <!-- 物资名称(只读) -->
  <!-- 序列号列 -->
 <!-- 物资序号列 -->
 <el-table-column label="物资序号" width="120" align="center">
    <template #default="scope">
      <el-input 
        v-model="scope.row.wuziId" 
        placeholder="请输入物资序号"
        size="small"
        class="compact-input"
      />
    </template>
  </el-table-column>


  <el-table-column label="物资名称" width="150" align="center">
    <template #default="scope">
      <el-input 
        v-model="scope.row.mingName" 
        placeholder="请输入物资名称"
        size="small"
        class="compact-input"
      />
    </template>
  </el-table-column>
  
  <!-- 入库序号列 -->
  <!-- <el-table-column label="入库序号" width="120" align="center">
    <template #default="scope">
      <el-input 
        v-model="scope.row.rukuId" 
        placeholder="请输入入库序号"
        size="small"
        class="compact-input"
      />
    </template>
  </el-table-column> -->


  
  <!-- 供应商列 -->
  <el-table-column label="供应商" width="150" align="center">
    <template #default="scope">
      <el-input 
        v-model="scope.row.wuziShangjia" 
        placeholder="请输入供应商"
        size="small"
        class="compact-input"
      />
    </template>
  </el-table-column>
  
  <!-- 生产日期列 -->
  <el-table-column label="生产日期" width="150" align="center">
    <template #default="scope">
      <el-date-picker
        v-model="scope.row.mingRiqi"
        type="date"
        value-format="YYYY-MM-DD"
        placeholder="请选择生产日期"
        size="small"
        style="width: 100%"
      />
    </template>
  </el-table-column>
  
  <!-- 过保日期列 -->
  <el-table-column label="过保日期" width="150" align="center">
    <template #default="scope">
      <el-date-picker
        v-model="scope.row.mingGuoriqi"
        type="date"
        value-format="YYYY-MM-DD"
        placeholder="请选择过保日期"
        size="small"
        style="width: 100%"
      />
    </template>
  </el-table-column>
  
  <!-- 购置日期列 -->
  <el-table-column label="购置日期" width="150" align="center">
    <template #default="scope">
      <el-date-picker
        v-model="scope.row.mingMairiqi"
        type="date"
        value-format="YYYY-MM-DD"
        placeholder="请选择购置日期"
        size="small"
        style="width: 100%"
      />
    </template>
  </el-table-column>
  
  <!-- 单价列 -->
  <el-table-column label="单价" width="120" align="center">
    <template #default="scope">
      <el-input 
        v-model="scope.row.mingDanjia" 
        placeholder="请输入单价"
        type="number"
        min="0"
        size="small"
        class="compact-input"
      />
    </template>
  </el-table-column>
  
  <!-- 是否可回收列 -->
  <el-table-column label="是否可回收" width="120" align="center">
    <template #default="scope">
      <el-select v-model="scope.row.mingHui" placeholder="请选择" size="small">
        <el-option label="是" value="1" />
        <el-option label="否" value="0" />
      </el-select>
    </template>
  </el-table-column>
  
  <!-- 数量列 -->
  <el-table-column label="数量" width="100" align="center">
    <template #default="scope">
      <el-input 
        v-model="scope.row.mingShuliang" 
        placeholder="请输入数量"
        type="number"
        min="1"
        size="small"
        class="compact-input"
      />
    </template>
  </el-table-column>
  
  <!-- 物资名称列 -->

  
  <!-- 物资规格列 -->
  <el-table-column label="物资规格" width="150" align="center">
    <template #default="scope">
      <el-input 
        v-model="scope.row.mingGuige" 
        placeholder="请输入物资规格"
        size="small"
        class="compact-input"
      />
    </template>
  </el-table-column>
  
  <!-- 状态列 -->
    <el-table-column 
  prop="mingZhuangtai"
  :formatter="(row) => row.mingZhuangtai = row.mingZhuangtai || '0'"
  v-show="false"
></el-table-column>
</el-table>
         </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="物资入库详情" v-model="viewOpen" width="700px" append-to-body>
  <div style="display: flex; flex-direction: column; max-height: 70vh;">
    <!-- 主表信息（固定不滚动） -->
    <div style="flex-shrink: 0; padding: 20px; overflow-y: auto;">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="入库ID">{{ viewForm.rukuId }}</el-descriptions-item>
        <el-descriptions-item label="仓库名称">{{ viewForm.cangku?.kuName }}</el-descriptions-item>
        <el-descriptions-item label="入库人">{{ viewForm.table12?.yName }}</el-descriptions-item>
        <el-descriptions-item label="入库单号">{{ viewForm.rukuDanhao }}</el-descriptions-item>
        <el-descriptions-item label="采购批次">{{ viewForm.rukuPici }}</el-descriptions-item>
        <el-descriptions-item label="入库日期">{{ parseTime(viewForm.rukuRukudate, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="捐赠用途">{{ viewForm.rukuTongtu }}</el-descriptions-item>
        <el-descriptions-item label="物资来源">{{ viewForm.rukuLaiyuan }}</el-descriptions-item>
      </el-descriptions>
    </div>

<!-- 物资明细表格（可左右滚动） -->
<div style="flex-grow: 1; overflow: hidden; display: flex; flex-direction: column; padding: 0 20px 20px;">
  <div style="font-weight: bold; margin: 10px 0 5px 0;">物资明细</div>
  <div style="flex-grow: 1; overflow: auto;">
    <el-table 
      :data="viewForm.mingxi ? [viewForm.mingxi] : []" 
      border 
      size="small"
      style="width: 100%;">
      <el-table-column prop="mingName" label="物资名称" width="120" fixed />
      <el-table-column prop="mingGuige" label="规格" width="120" />
      <el-table-column prop="wuziShangjia" label="供应商" width="120" />
      <el-table-column prop="mingDanjia" label="单价" width="100" align="right">
        <template #default="scope">
          {{ scope.row.mingDanjia ? '¥' + scope.row.mingDanjia : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="mingShuliang" label="数量" width="80" align="center" />
      <el-table-column prop="mingHui" label="是否可回收" width="100" align="center">
        <template #default="scope">
          {{ scope.row.mingHui === 1 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column prop="mingZhuangtai" label="状态" width="100" align="center">
        <template #default="scope">
          {{ scope.row.mingZhuangtai === 0 ? '入库' : '出库' }}
        </template>
      </el-table-column>
      <el-table-column prop="mingRiqi" label="生产日期" width="120">
        <template #default="scope">
          {{ parseTime(scope.row.mingRiqi, '{y}-{m}-{d}') || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="mingGuoriqi" label="过期日期" width="120">
        <template #default="scope">
          {{ parseTime(scope.row.mingGuoriqi, '{y}-{m}-{d}') || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="mingMairiqi" label="购置日期" width="120">
        <template #default="scope">
          {{ parseTime(scope.row.mingMairiqi, '{y}-{m}-{d}') || '-' }}
        </template>
      </el-table-column>
    </el-table>
  </div>
</div>
  </div>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="viewOpen = false">关 闭</el-button>
    </div>
  </template>
</el-dialog>

<!-- 选择仓库明细的弹窗 -->
<el-dialog 
  title="物资信息" 
  v-model="warehouseDetailVisible" 
  width="80%"
  append-to-body>

  <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="mingxiAdd"
          v-hasPermi="['jiuzai:cangkumingxi:add']"
        >新增</el-button>
      </el-col>


  <el-table :data="wuzixinxiList" border style="width: 100%">
    <el-table-column label="序号" align="center" prop="wuziId" />
      <el-table-column label="物资编号" align="center" prop="wuziBianhao" />
      <el-table-column label="物资名称" align="center" prop="wuziName" />
      <el-table-column label="物资类别" align="center" prop="leibieId">
        <template v-slot="scope">
          <span v-if="scope.row.leibieId === scope.row.wuzileibie.leiId">
            {{ scope.row.wuzileibie.leiName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="是否为回收的物资" align="center" prop="wuziHui" />
      <el-table-column label="物资单位" align="center" prop="wuziDanwei" />
      <el-table-column label="物资数量" align="center" prop="wuziShu" />
      <el-table-column label="物资外部存储" align="center" prop="wuziWaibu" />
    <!-- 添加选择操作列 -->
    <el-table-column label="操作" width="120" align="center">
      <template #default="scope">
        <el-button 
          type="primary" 
          size="small" 
          @click="selectWarehouseItem(scope.row)">
          选择
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <template #footer>
    <div class="dialog-footer">
      <el-button @click="warehouseDetailVisible = false">关闭</el-button>
    </div>
  </template>
</el-dialog>



<!-- 增加区域 -->

<el-dialog :title="title" v-model="warehouseDetailAddVisible" width="500px" append-to-body>
  <el-form ref="cangkumingxiRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物资序号" prop="wuziId">
          <el-input v-model="form.wuziId" placeholder="请输入物资序号" />
        </el-form-item>
        <el-form-item label="入库序号" prop="rukuId">
          <el-input v-model="form.rukuId" placeholder="请输入入库序号" />
        </el-form-item>
        <el-form-item label="出库序号" prop="cId">
          <el-input v-model="form.cId" placeholder="请输入出库序号" />
        </el-form-item>
        <el-form-item label="供应商" prop="wuziShangjia">
          <el-input v-model="form.wuziShangjia" placeholder="请输入供应商" />
        </el-form-item>
        <el-form-item label="生产日期" prop="mingRiqi">
          <el-date-picker clearable
            v-model="form.mingRiqi"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择生产日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="过保日期" prop="mingGuoriqi">
          <el-date-picker clearable
            v-model="form.mingGuoriqi"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择过保日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="购置日期" prop="mingMairiqi">
          <el-date-picker clearable
            v-model="form.mingMairiqi"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择购置日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="单价" prop="mingDanjia">
          <el-input v-model="form.mingDanjia" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="是否可回收" prop="mingHui">
          <el-input v-model="form.mingHui" placeholder="请输入是否可回收" />
        </el-form-item>
        <el-form-item label="数量" prop="mingShuliang">
          <el-input v-model="form.mingShuliang" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="物资名称" prop="mingName">
          <el-input v-model="form.mingName" placeholder="请输入物资名称" />
        </el-form-item>
        <el-form-item label="物资规格" prop="mingGuige">
          <el-input v-model="form.mingGuige" placeholder="请输入物资规格" />
        </el-form-item>
        <el-form-item label="状态(0.入库1.出库)" prop="mingZhuangtai">
          <el-input v-model="form.mingZhuangtai" placeholder="请输入状态(0.入库1.出库)" />
        </el-form-item>
      </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button type="primary" @click="mingxisubmitForm">确 定</el-button>
      <el-button @click="warehouseDetailAddVisible = false">取 消</el-button>
    </div>
  </template>
</el-dialog>


  </div>
</template>

<script setup name="Wuziruku">
import { listWuziruku, getWuziruku, delWuziruku, addWuziruku, updateWuziruku } from "@/api/jiuzai/wuziruku"
import { listCangkumingxi, getCangkumingxi, delCangkumingxi, addCangkumingxi, updateCangkumingxi } from "@/api/jiuzai/cangkumingxi"
import { listCangku } from "@/api/cangku/cangku"
import { listWuzi } from  "@/api/jiuzai/wuzi"
import { listWuzixinxi, getWuzixinxi, updateWuzixinxi } from "@/api/jiuzai/wuzixinxi"


import { onMounted } from 'vue';
const { proxy } = getCurrentInstance()

const wuzirukuList = ref([])
const open = ref(false)
const viewOpen = ref(false) // 新增查看对话框状态
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const viewForm = ref({}) // 新增查看表单数据
const wuzixinxiList = ref([])//物资信息列表
const cangkuList = ref([])
const wuziList = ref([])
const warehouseDetailAddVisible = ref(false)
const warehouseDetailVisible = ref(false)
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    rukuCangku: null,
    rukuRukudate: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询wuziruku列表 */
function getList() {
  loading.value = true
  listWuziruku(queryParams.value).then(response => {
    wuzirukuList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

function getCangkuList() {
  loading.value = true
  listCangku(queryParams.value).then(response => {
    cangkuList.value = response.rows
    // console.log(cangkuList.value)
    loading.value = false
  })
}
// 查看全部物资信息
function handleSelectMingxi() {
  loading.value = true
  warehouseDetailVisible.value = true 
  listWuzixinxi(queryParams.value).then(response => {
    wuzixinxiList.value = response.rows
    console.log(wuzixinxiList)
    total.value = response.total
    loading.value = false
  })
}
// 增加
/** 新增按钮操作 */
function mingxiAdd() {
  zengjia()
  warehouseDetailAddVisible.value = true
  title.value = "添加物资出入库明细"
}

// 在 <script setup> 中添加这个方法
function selectWarehouseItem(row) {
  if (!form.value.mingxiList) {
    form.value.mingxiList = []
  }
  
  // 将物资信息映射为明细格式
  const detailItem = {
    mingName: row.wuziName,  // 映射物资名称
    mingGuige: '',           // 初始化规格
    wuziShangjia: '',        // 初始化供应商
    mingDanjia: 0,           // 初始化单价
    mingShuliang: 1,         // 默认数量1
    wuziId: row.wuziId       // 保留物资ID
  }
  
  form.value.mingxiList.push(detailItem)
  warehouseDetailVisible.value = false
  proxy.$modal.msgSuccess("已选择物资明细")
}





function zengjia() {
  form.value = {
    mingId: null,
    wuziId: null,
    rukuId: null,
    cId: null,
    wuziShangjia: null,
    mingRiqi: null,
    mingGuoriqi: null,
    mingMairiqi: null,
    mingDanjia: null,
    mingHui: null,
    mingShuliang: null,
    mingName: null,
    mingGuige: null,
    mingZhuangtai: null
  }
  proxy.resetForm("cangkumingxiRef")
}


/** 提交按钮 */
function mingxisubmitForm() {
  proxy.$refs["cangkumingxiRef"].validate(valid => {
    if (valid) {
      addCangkumingxi(form.value).then(response => {
        proxy.$modal.msgSuccess("新增成功")
        warehouseDetailAddVisible.value = false
        // 重新加载明细列表
        listCangkumingxi(queryParams.value).then(res => {
          warehouseDetailList.value = res.rows
        })
      })
    }
  })
}

function getjueseList() {
  loading.value = true
  listWuzi(queryParams.value).then(response => {
    wuziList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}


onMounted(() => {
  getCangkuList()
  getjueseList()
})


// function getcList() {
//   loading.value = true
//   listCangku(queryParams.value).then(response => {
//     cangkuList.value = response.rows
//     total.value = response.total
//     loading.value = false
//   })
// }


/** 查看按钮操作 */
function handleBatchView() {
  if (ids.value.length === 0) {
    proxy.$message.warning("请先选择要查看的记录");
    return;
  }
  if (ids.value.length > 1) {
    proxy.$message.warning("只能选择一条记录查看");
    return;
  }
  
  const rukuId = ids.value[0];
  getWuziruku(rukuId).then(response => {
    viewForm.value = response.data;
    console.log(viewForm.value);
    viewOpen.value = true;
  });
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    rukuId: null,
    kuId: null,
    yId: null,
    rukuDanhao: null,
    rukuPici: null,
    rukuCangku: null,
    rukuRukudate: null,
    rukuTongtu: null,
    rukuLaiyuan: null,
    rukuQuyu: null,
    dizhiId: null,
    mingxiList: [] // 添加空数组初始化
  }
  proxy.resetForm("wuzirukuRef")
}



/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.rukuId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}


/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加物资入库"
  if (!form.value.rukuDanhao) {
    const now = new Date()
    const timePart = now.toISOString().replace(/[-:T.]/g, '').slice(2, 14)
    form.value.rukuDanhao = `RK${timePart}`
  }
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset(); // 重置表单
  const _rukuId = row.rukuId || ids.value[0]; // 确保获取单个入库单ID
  
  try {
    // 1. 获取主表数据
    const mainResponse = await getWuziruku(_rukuId);
    form.value = {
      ...mainResponse.data,
      mingxiList: [] // 初始化为空数组
    };

    // 2. 获取关联的明细数据 - 使用getCangkumingxi获取单条明细
    const detailResponse = await getCangkumingxi(_rukuId);
    console.log("明细数据返回:", detailResponse); // 调试用
    
    // 3. 处理明细数据
    if (detailResponse.data) {
      form.value.mingxiList = [{
        mingId: detailResponse.data.mingId,
        wuziId: detailResponse.data.wuziId,
        rukuId: detailResponse.data.rukuId,
        mingName: detailResponse.data.mingName || '',
        mingGuige: detailResponse.data.mingGuige || '',
        wuziShangjia: detailResponse.data.wuziShangjia || '',
        mingDanjia: detailResponse.data.mingDanjia || 0,
        mingShuliang: detailResponse.data.mingShuliang || 1,
        mingRiqi: detailResponse.data.mingRiqi || null,
        mingGuoriqi: detailResponse.data.mingGuoriqi || null,
        mingMairiqi: detailResponse.data.mingMairiqi || null,
        mingHui: detailResponse.data.mingHui || '0',
        mingZhuangtai: detailResponse.data.mingZhuangtai || '0'
      }];
    }

    open.value = true;
    title.value = "修改物资入库";
  } catch (error) {
    console.error("获取数据失败:", error);
    proxy.$modal.msgError("加载数据失败，请检查控制台");
    
    // 即使明细加载失败也打开表单，只显示主表数据
    open.value = true;
    title.value = "修改物资入库";
  }
}
// 修改submitForm方法，处理明细更新
async function submitForm() {
  proxy.$refs["wuzirukuRef"].validate(async (valid) => {
    if (valid) {
      try {
        // 1. 准备主表数据
        const mainFormData = { ...form.value }
        delete mainFormData.mingxiList

        // 2. 提交主表
        let res
        if (form.value.rukuId) {
          res = await updateWuziruku(mainFormData)
        } else {
          res = await addWuziruku(mainFormData)
        }

        const rukuId = res?.data?.rukuId || form.value.rukuId
        if (!rukuId) throw new Error("未获取到入库ID")

        // 3. 处理明细数据
        if (form.value.mingxiList?.length > 0) {
          await handleMingxiList(rukuId)
          
          // 4. 更新物资信息表中的数量
          await updateWuziQuantities(form.value.mingxiList)
        }

        proxy.$modal.msgSuccess("操作成功")
        open.value = false
        getList()
      } catch (error) {
        console.error("提交错误:", error)
        proxy.$modal.msgError(`操作失败: ${error.message}`)
      }
    }
  })
}

// 新增方法：更新物资信息表中的数量
async function updateWuziQuantities(mingxiList) {
  try {
    // 遍历所有明细项
    for (const item of mingxiList) {
      if (!item.wuziId || !item.mingShuliang) continue
      
      // 获取当前物资信息
      const currentWuzi = await getWuzixinxi(item.wuziId)
      if (!currentWuzi.data) continue
      
      // 计算新数量（原数量 + 入库数量）
      const newQuantity = (currentWuzi.data.wuziShu || 0) + Number(item.mingShuliang)
      
      // 更新物资信息
      await updateWuzixinxi({
        ...currentWuzi.data,
        wuziShu: newQuantity
      })
    }
  } catch (error) {
    console.error("更新物资数量失败:", error)
    throw error
  }
}

// 新增处理明细列表的方法
async function handleMingxiList(rukuId) {
  try {
    if (!form.value.mingxiList?.length) return

    const promises = form.value.mingxiList.map(item => {
      const detailData = {
        ...item,
        rukuId: Number(rukuId)
      }
      
      if (item.mingId) {
        // 已有ID表示是已存在的记录，执行更新
        return updateCangkumingxi(detailData)
      } else {
        // 新记录执行添加
        return addCangkumingxi(detailData)
      }
    })

    await Promise.all(promises)
    proxy.$modal.msgSuccess("物资明细处理成功")
  } catch (error) {
    console.error("明细处理失败:", error)
    throw error
  }
}



// function submitForm() {
//   proxy.$refs["wuzirukuRef"].validate(valid => {
//     if (valid) {
//       if (form.value.rukuId != null) {
//         updateWuziruku(form.value).then(response => {
//           proxy.$modal.msgSuccess("修改成功")
//           open.value = false
//           getList()
//         })
//       } else {
//         addWuziruku(form.value).then(response => {
//           proxy.$modal.msgSuccess("新增成功")
//           open.value = false
//           getList()
//         })
//       }
//     }
//   })
// }

/** 删除按钮操作 */
function handleDelete(row) {
  const _rukuIds = row.rukuId || ids.value
  proxy.$modal.confirm('是否确认删除wuziruku编号为"' + _rukuIds + '"的数据项？').then(function() {
    return delWuziruku(_rukuIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('jiuzai/wuziruku/export', {
    ...queryParams.value
  }, `wuziruku_${new Date().getTime()}.xlsx`)
}

getList()
</script>
